import { viewUtils, esriUtils } from '@/utils/arcgis';
import _ from 'lodash';
import * as actions from '../constants/action-types';

const ags = {};
window.agsGlobal = ags;

function createView(opts = {}) {
  // Detect if 'createLogger' was passed directly to 'applyMiddleware'.
  if (opts.getState && opts.dispatch) {
    return () => next => action => next(action);
  }

  return store => next => async action => {
    switch (action.type) {
      case actions.INIT_WEBSCENE: {
        const { payload } = action;
        const { container, basemapID } = payload;

        // DOM container not defined
        if (!container) break;

        // 设置proxy和portal地址
        await esriUtils.setEsriConfig({
          // proxyUrl: window.appcfg.proxy,
          portal: window.appcfg.portal,
        });
        // 创建基础底图
        let _basemapConfig =
          window.basemapConfig[JSON.stringify(store.getState().app.basemapIndex)];

        let params = new URL(document.location).searchParams;
        let bmapIndex = params.get('bmap');

        if (bmapIndex) {
          try {
            _basemapConfig = window.basemapConfig[bmapIndex];
          } catch (error) {
            _basemapConfig = window.basemapConfig[0];
          }
        }
        // console.log(store.getState().app.basemapIndex)

        // 根据项目不同切换初始位置
        let _cameraConfig =
          store.getState().app.basemapIndex == 3
            ? window.appcfg.jsapiConfig.initialCamera
            : window.appcfg.jsapiConfig.projInitialCamera;

        // console.log(_cameraConfig)
        const basemap = await viewUtils.createBasemap(_basemapConfig);
        const param = {
          container: container,
          basemap: basemap,
          basemapID: basemapID,
          camera: _cameraConfig,
        };
        // 初始化场景
        ags.view = await viewUtils.initSceneView(param, store);
        store.dispatch({ type: 'scheme/updateScenesView', payload: ags.view });
        // When initialized...
        return ags.view.when(() => {
          // after view created
          store.dispatch({ type: 'app/updateViewLoaded', payload: true });

          ags.view.watch(
            'zoom',
            _.debounce((newVal, oldVal) => {
              const kanbanLvl = store.getState().kanban.level;
              if (newVal > 12.7) {
                if (kanbanLvl === 'project') {
                  store.dispatch({ type: 'kanban/updateState', payload: { level: 'section' } });
                }
              } else {
                if (kanbanLvl !== 'project') {
                  store.dispatch({ type: 'kanban/updateState', payload: { level: 'project' } });
                }
              }
            }, 50),
          );
        });
      }

      default: {
        next(action);
        break;
      }
    }

    return Promise.resolve();
  };
}

export { createView };
